package com.lei.zjs.shiro;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.struts2.ServletActionContext;

import com.lei.zjs.dao.FunctionDao;
import com.lei.zjs.dao.UserDao;
import com.lei.zjs.utils.BOSContext;
import com.lei.zjs.vo.Function;
import com.lei.zjs.vo.User;

/**
 * zjs安全数据桥
 * @author Spinacia
 *
 */
public class BOSRealm extends AuthorizingRealm{

	@Resource
	private UserDao userDao;
	@Resource
	private FunctionDao functionDao;
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authenticationToken) throws AuthenticationException {
		
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		String username = token.getUsername();
		//通过用户名查询用户
		User user = userDao.findUserByUsername(username);
		if (user == null) {
			//没查到用户,说明用户名不存在
			return null;
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
		return info;		
	}
	
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		User user = (User) principals.getPrimaryPrincipal();
		if ("admin".equals(user.getUsername())) {
			//超级管理员,赋予所有权限
			List<Function> list = functionDao.findAll();
			for (Function function : list) {
				info.addStringPermission(function.getCode());
			}
		}else{
			List<Function> list = functionDao.findByUser(user.getId());
			for (Function function : list) {
				info.addStringPermission(function.getCode());
			}
		}
		return info;
	}
}
